<template>
    <div class="app-container">
        <el-row class="marginBottom10">
            <el-col :span="5" style="font-weight: 600;">订单号：{{rowData.orderNo}} <el-icon  @click="copyText(rowData.orderNo)"><DocumentCopy /></el-icon> </el-col>
            <template v-if="rowData.companyId == '2' && rowData.agentId == '3'">
                <el-col :span="5" style="font-weight: 600;">业务编号：{{rowData.businessNo}} <el-icon><DocumentCopy  @click="copyText(rowData.businessNo)"/></el-icon> </el-col>
            </template>  
        </el-row>
        <!-- <Steps :status="_stepStatus" :cancellationStatus="_cancellationStatus" :frontNodeReviewStatus="_frontNodeReviewStatus" :currentNodeType="_currentNodeType"  :remark="rowData.remark" :payStatus="rowData.payStatus"></Steps> -->
        <el-card>
            <StepsTool :status="_stepStatus" :orderData="rowData" :businessRoleEnum="businessRoleEnum" ></StepsTool>
        </el-card>
        <Signature class="signature-position" :status="_stepStatus" :currentNodeType="_currentNodeType" :businessRoleEnum="businessRoleEnum" style="z-index: 9;" ></Signature>
        <el-row gutter="20" class="marginTop10">
            <el-col :span="12">
                <el-card>
                    <el-row align="middle">
                        <el-col :span="12"><h4 v-if="rowData">{{ rowData.companyName }}</h4></el-col>
                        <el-col :span="12" class="text-right">
                            <h3 style="color: #2158F3;font-weight: 600;">提箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</h3>
                        </el-col>
                    </el-row>
                    <el-divider border-style="dashed" style="margin-top: 0px;"/>
                    <el-row>
                        <el-col :span="24">
                            <el-table ref="myTable" :data="tableInfo" style="width: 100%;height:225px;" :row-class-name="tableRowClassName"> 
                                <el-table-column prop="returnCity" label="还箱城市" align="center">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.returnCityId" placeholder="请选择城市" @change="changeCity" :disabled="_stepStatus >= 3 || businessRoleEnum == '5'?true:false" style="width: 100%">
                                            <el-option v-for="(item,index) in scope.row.returnCity" :key="index" :label="item.returnCityName" :value="item.returnCityId"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="unitPrice" label="单价" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.unitPrice" placeholder="请输入单价" :disabled="_stepStatus >= 3 || businessRoleEnum == '5'?true:false" :formatter="formatterNumber" :parser="formatterNumber" class="el-price" style="width: 100%;">
                                            <template #prefix>
                                                <el-select v-model="scope.row.currency" placeholder="Select" :disabled="_stepStatus >= 3 || businessRoleEnum == '5'?true:false" style="width: 60px" >
                                                    <el-option label="＄" value="USD"></el-option>
                                                    <el-option label="￥" value="CNY"></el-option>
                                                </el-select>
                                            </template>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="boxQuantity" label="下单量" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.boxQuantity" placeholder="请输入箱量" :disabled="_stepStatus >= 3 || businessRoleEnum == '5'?true:false" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" class="input-width"/>
                                    </template>
                                </el-table-column>
                                <template v-if="_stepStatus >= 20">
                                    <el-table-column prop="actualBoxQuantity" label="实还量" align="center">
                                        <template #default="scope">
                                            <el-input v-model="scope.row.actualBoxQuantity" placeholder="请输入箱量" :disabled="_stepStatus >= 3 || businessRoleEnum == '5'?true:false" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" class="input-width"/>
                                        </template>
                                    </el-table-column>
                                </template>
                                
                                <el-table-column prop="city" align="center" width="50">
                                    <template  #default="scope"  v-if="businessRoleEnum == '10' && _stepStatus < 3"><el-icon size="20" class="cursor" @click="handleDelete1(scope.$index)"><Remove /></el-icon></template>
                                </el-table-column>
                                
                            </el-table>
                        </el-col>
                        <el-col :span="24" class="marginTop5">
                            <el-row align="middle">
                                <el-col :span="12">
                                    <template v-if="businessRoleEnum == '10'">
                                        <template v-if="_stepStatus < 3">
                                            <el-icon :size="25" color="#2158F3" class="cursor"  @click="handleAdd1"><CirclePlus /></el-icon>
                                        </template>
                                    
                                        <template v-if="_stepStatus == 20 || _stepStatus == 25">
                                            <el-icon :size="25" color="#2158F3" class="cursor"  @click="showAddReturnCity"><CirclePlus /></el-icon>
                                        </template>
                                    </template>
                                </el-col>
                                <el-col :span="12" class="text-right">
                                    <span class="_asterisk">结算流向：</span>
                                    <template v-if="_stepStatus < 3 && businessRoleEnum == 10">
                                        <el-radio-group v-model="direction">
                                            <el-radio value="-1" size="large">应付</el-radio>
                                            <el-radio value="1" size="large">应收</el-radio>
                                        </el-radio-group>
                                    </template>
                                    <template v-else>
                                        <template v-if="direction == '-1'">应付</template>
                                        <template v-else-if="direction == '1'">应收</template>
                                    </template>
                                    <!--  -->
                                    
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card style="height: 378px;">
                    <el-row class="marginTop10">
                        <el-col :span="3" class="text-right">总箱量：</el-col><el-col :span="4">{{totalBoxNum}}</el-col>
                        <el-col :span="4" style="color:#22A86D;">已提：{{rowData.packedQuantity}}</el-col>
                        <el-col :span="4" style="color:#ff0000;">未提：{{Number(rowData.boxQuantity) - Number(rowData.packedQuantity)}}</el-col>
                        <template v-if="_stepStatus >= 20">
                            <el-col :span="4" style="color:#22A86D;">已还：{{rowData.returnedQuantity}}</el-col>
                            <el-col :span="4" style="color:#ff0000;">未还：{{Number(rowData.boxQuantity) - Number(rowData.returnedQuantity)}}</el-col>
                        </template>
                        <template v-else><el-col :span="24" ></el-col></template>
                        <el-col :span="3" class="text-right marginTop25">箱型：</el-col><el-col :span="4" class="marginTop25">{{basicConfig.boxTypeInfo1[rowData.boxType]}}</el-col>
                        <el-col :span="8" class="marginTop25">箱况：{{basicConfig.boxConditionInfo2[rowData.boxCondition]}}</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">超期费：</el-col><el-col :span="20">超期1天，{{basicConfig.currency2[rowData.overdueFeeCurrency]}}{{rowData.overdueFeeDay}}/箱/天；超期{{rowData.lossDay}}天后仍未还箱，视为灭失，灭失费为{{basicConfig.currency2[rowData.overdueFeeCurrency]}}{{rowData.lossFee}}</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">货品名称：</el-col><el-col :span="20">{{rowData.cargoName || '暂无货品名称'}}</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">联系人：</el-col><el-col :span="4">{{rowData.agentUserName}}</el-col> 
                        <el-col :span="8">联系电话：+{{rowData.agentUserAreaCode}} {{rowData.agentUserTel}} </el-col>
                        <el-col :span="8">修箱费：还箱时，实报实销</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">特殊说明：</el-col>
                        <el-col :span="20">
                            <template v-if="businessRoleEnum == '5'"> 
                                <template v-if="rowData.specialNote">
                                    <el-input v-model="rowData.specialNote" style="width: 100%" :rows="3" type="textarea" disabled />
                                </template>
                                <template v-else>
                                    <el-input v-model="rowData.specialNote" style="width: 100%" :rows="3" type="textarea" disabled />
                                </template>
                            </template>
                            <template v-else-if="businessRoleEnum == '10'">
                                <template v-if="_stepStatus < 3"> <!--3:待签署-->
                                    <el-input v-model="rowData.specialNote" style="width: 100%" :rows="3" type="textarea" />
                                </template>
                                <template v-else>
                                    <template v-if="rowData.specialNote">
                                        <el-input v-model="rowData.specialNote" style="width: 100%" :rows="3" type="textarea" disabled />
                                    </template>
                                    <template v-else>
                                        <el-input v-model="rowData.specialNote" style="width: 100%" :rows="3" type="textarea" disabled/>
                                    </template>
                                </template>
                            </template>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>

        <el-card class="marginTop20 marginBottom20">
            <span class="_before">订单信息</span>
            <el-row class="marginTop20" align="middle">
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">预计提箱日期： </span></el-col>
                <el-col :span="5">
                    <!-- {{formatDate(rowData.planPickupDate,2)}} -->
                    <template v-if="_stepStatus < 3 && businessRoleEnum == '10'">
                        <el-date-picker v-model="rowData.planPickupDate" type="date" placeholder="提箱日期" />
                    </template>
                    <template v-else>
                        {{formatDate(rowData.planPickupDate,2)}}
                    </template>
                </el-col>
                <el-col :span="2" class="text-right"><span class="_asterisk">支付方式： </span></el-col>
                <el-col :span="6">
                    <template v-if="_stepStatus < 3">
                        <template v-if="sourceType == 'edit'">
                            <el-select v-model="paymentMethod" style="width:200px">
                                <el-option label="对公转账" value="5"/>
                                <el-option label="在线支付" value="10"/>
                            </el-select>
                        </template>
                        <template v-if="sourceType == 'view'">{{basicConfig.paymentMethod[paymentMethod]}}</template>
                    </template>
                    <template v-else>{{basicConfig.paymentMethod[paymentMethod]}}</template>
                </el-col>
                <el-col :span="2" class="text-right"><span class="_asterisk">结算账期： </span></el-col>
                <el-col :span="6"> 
                    <template v-if="_stepStatus < 3"> 
                        <template v-if="sourceType == 'edit'">
                            <el-input v-model="rowData.period" placeholder="请输入天数" style="width:200px">
                                <template #append>天</template>
                            </el-input>
                        </template>
                        <template v-if="sourceType == 'view'">{{rowData.period}} 天</template>
                    </template>
                    <template v-else>{{rowData.period}}天</template>
                </el-col>
                <el-col :offset="1" :span="2" class="text-right marginTop20"><span class="_asterisk">箱使期：</span></el-col>
                <el-col :span="6" class="marginTop20"> 
                    <template v-if="businessRoleEnum == '10' && _stepStatus < 3">
                        <el-input v-model="rowData.boxUsagePeriod" placeholder="请输入天数" style="width:200px">
                            <template #append>天</template>
                        </el-input>
                    </template>
                    <template v-else> {{rowData.boxUsagePeriod}}天</template>
                </el-col>
            </el-row>
            <el-divider  border-style="dashed"/>
            <el-row class="marginBottom20" align="middle">
                <el-col :offset="1" :span="2" class="text-right"><span>经办人：</span></el-col>
                <el-col :span="5">
                    <template v-if="businessRoleEnum == '10'">{{rowData.boxEastUserName}}</template> <!--箱东公司-->
                    <template v-else-if="businessRoleEnum == '5'">{{rowData.agentUserName}}</template> <!--货代公司-->
                    <template v-else>--</template>
                </el-col>
                <template v-if="businessRoleEnum == '10'">
                    <el-col :span="2" class="text-right"><span class="_asterisk">操作员：</span></el-col>
                    <template v-if="_stepStatus < 3">
                        <el-col :span="3">
                            <el-select v-model="param.boxEastOperatorUserId" filterable>
                                <el-option v-for="(user, index) in param.userSimpleList" :key="index" :label="user.nickname" :value="user.userId" />
                            </el-select>
                        </el-col>
                    </template>
                    <template v-else>{{rowData.boxEastOperatorUserName}}</template>
                </template>
            </el-row>
            <template v-if="businessRoleEnum == '5'">
                <el-row v-for="(item,index) in allocation" :key="index" align="middle" class="marginBottom10">
                    <el-col :offset="1" :span="2" class="text-right"><span>业务员：</span></el-col> 
                    <el-col :span="5">{{item.businessUserName}}</el-col>
                    <el-col :span="2" class="text-right"><span>操作员：</span></el-col>
                    <el-col :span="6">{{item.operateUserName}}</el-col>
                    <el-col :span="2" class="text-right"><span>业务编号：</span></el-col>
                    <el-col :span="4">{{item.businessNo}}</el-col>
                </el-row>
            </template>
            
            <el-divider  border-style="dashed"/>
            <el-row>
                <el-col :offset="1" :span="2" class="text-right"><span>留言：</span></el-col>
                <el-col :span="20">{{rowData.leaveMsg}}</el-col>
            </el-row>
        </el-card>
        <template v-if="_stepStatus == 40">
            <el-card class="marginTop20" >
                <span class="_before">取消订单信息</span>
                <el-row justify="center" align="middle">
                    <el-col :span="24" class="text-center marginTop20 marginBottom20">取消原因：{{rowData.remark}}</el-col>
                    <template v-if="rowData.canceledType == '5'"> <!--箱东取消 -->
                        <template v-if="businessRoleEnum == '5'"> <!--货代确认-->
                            <template v-if="_currentNodeType != 15">
                                <el-col :span="3" @click="rejected" class="text-center"><el-button type="warning">拒绝</el-button></el-col>
                                <el-col :span="3" @click="approved" class="text-center"><el-button type="danger">同意</el-button></el-col>
                            </template>
                        </template>

                        <template v-if="businessRoleEnum == '10'"> <!--谁发起取消 拒绝之后 谁确认-->
                            <template v-if="_currentNodeType == 15">
                                <el-col :span="3" @click="approved(2)" class="text-center"><el-button type="warning">确认</el-button></el-col>
                            </template>
                        </template> 
                    </template>
                    <template v-if="rowData.canceledType == '10'"> <!--货代取消 -->
                        <template v-if="businessRoleEnum == '10'"> <!--箱东确认-->
                            <template v-if="_currentNodeType == 15">
                                <el-col :span="3" @click="rejected" class="text-center"><el-button type="warning">确认</el-button></el-col>
                            </template>
                            <template v-else>
                                <el-col :span="3" @click="rejected" class="text-center"><el-button type="warning">拒绝</el-button></el-col>
                                <el-col :span="3" @click="approved" class="text-center"><el-button type="danger">同意</el-button></el-col>
                            </template>
                        </template>
                        <template v-if="businessRoleEnum == '5'"> <!--谁发起取消 拒绝之后 谁确认-->
                            <template v-if="_currentNodeType == 15">
                                <el-col :span="3" @click="approved(2)" class="text-center"><el-button type="warning">确认</el-button></el-col>
                            </template>
                        </template> 
                    </template>
                </el-row>
            </el-card>
        </template>
        
        <!-- 取消订单  申请发票  确认订单 签署  开提箱单-->
        <template v-if="_stepStatus != 35 && _stepStatus != 15 && _stepStatus != 40"> 
            <el-affix v-if="_stepStatus < 15" position="bottom">
                <el-card>
                    <el-row align="middle" justify="center">
                        <el-col :span="2" v-if="_stepStatus < 15"><el-button type="warning" @click="toCancelOrder">取消订单</el-button></el-col>
                        <template v-if="_stepStatus == 2 && businessRoleEnum == '10'">
                            <el-col :span="2"><el-button type="primary" @click="confirmOrder">确认订单</el-button></el-col>
                        </template>
                        <template v-if="_stepStatus == 3">
                            <el-col :span="2"><el-button type="primary" @click="signContract">签署</el-button></el-col>
                            <template v-if="businessRoleEnum == '10'">
                                <el-col :span="2"><el-button type="primary" @click="completeSigning(rowData.id)">完成签署</el-button></el-col>
                            </template>
                        </template>
                        <template  v-if="businessRoleEnum == '10' && (rowData.packingAllocationQuantity < rowData.boxQuantity)">
                            <template v-if="_stepStatus == 5 || _stepStatus == 10 || _stepStatus == 15">
                                <el-col :span="2"><el-button type="primary" @click="handlePacking">开提箱单</el-button></el-col>
                            </template>
                        </template>
                        <!-- <template v-if="businessRoleEnum == '5'" >
                            <template v-if="_stepStatus > 3 && rowData.invoiceStatus == '5'">
                                <el-col :span="2"><el-button type="primary" @click="invoiceDialog = true">申请发票</el-button></el-col>
                            </template>
                        </template> -->
                    </el-row>
                </el-card>
            </el-affix>
        </template>



        <el-dialog v-model="eqbDialog" width="90%" :with-header="false" @close="closeEQianBao">
            <iframe v-if="eqbDialog" :src="eqbUrl" width="100%" height="750px" frameborder="0" ></iframe>
        </el-dialog>

        <!-- 开提箱单 -->
        <el-dialog v-model="dackingDialog"  v-if="dackingDialog" :show-close="false" size="40%" :with-header="false"> 
            <el-row>
                <el-col :span="6">
                <span class="_before">开提箱单</span>
                </el-col>
            </el-row>
            <el-row align="middle">
                <el-col :span="4"><redStar />提箱单类型</el-col>
                <el-col :span="8" >
                    <el-radio-group v-model="packingType">
                        <el-radio value = "5" size="large">自有箱</el-radio>
                        <el-radio value = "15" size="large">外调箱</el-radio>
                    </el-radio-group>
                </el-col>
            </el-row>
            <OwnBox v-if="packingType == '5' " :packingInfo="param.packingInfo"  :orderType="5" @closeDialog="closeDialog"></OwnBox> 
            <!--自有箱-->
            <ExternalBox v-if="packingType == '15'" :packingInfo="param.packingInfo" :orderType="5" @closeDialog="closeDialog"></ExternalBox>
        </el-dialog>
        <!-- 申请发票 -->
        <el-dialog v-model="invoiceDialog" :show-close="false" size="40%" :with-header="false">
            <span class="_before">申请发票</span>
            <invoiceTemplate style="margin-top: 10px;"></invoiceTemplate>
            <el-row class="marginTop20">
                <el-col :span="6" class="text-right marginTop10">发票状态</el-col><el-col :offset="5" :span="10" class="marginTop10">{{ { 5: '未申请', 10: '待开票', 15: '已开票' }[rowData.invoiceStatus] }}</el-col>
                <el-col :span="6" class="text-right marginTop10">发票内容</el-col><el-col :offset="5" :span="10" class="marginTop10">租箱明细</el-col>
                <el-col :span="6" class="text-right marginTop10">发票抬头</el-col><el-col :offset="5" :span="10" class="marginTop10">{{ rowData.invoiceTitle }}</el-col>
                <el-col :span="6" class="text-right marginTop10">发票号码</el-col><el-col :offset="5" :span="10" class="marginTop10">{{ rowData.invoiceNo }}</el-col>
                <el-col :span="6" class="text-right marginTop10">联系集装箱公司</el-col><el-col :offset="5" :span="10" class="marginTop10">{{ rowData.tel }}</el-col>
                <el-col :span="6" class="text-right marginTop10">在线咨询</el-col><el-col :offset="5" :span="10" class="marginTop10">联系客服</el-col>
            </el-row>
            <el-form ref="invoiceRef" :model="rowData" v-if="rowData.invoiceStatus == '5'" label-width="auto" :rules="rules" style="margin-top: 30px;">
                <el-form-item label="发票类型" prop="invoiceType">
                    <el-radio-group v-model="rowData.invoiceType">
                        <el-radio value="5" label="增值税普通发票"></el-radio>
                        <el-radio value="10" label="增值税专用发票"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="企业名称" prop="invoiceTitle">
                    <el-input v-model="rowData.invoiceTitle" type="textarea" style="width: 500px;" maxlength="200" show-word-limit rows="1" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="统一社会信用代码" prop="invoiceTaxNum">
                    <el-input v-model="rowData.invoiceTaxNum" type="textarea" style="width: 500px;" maxlength="18" rows="1" placeholder="请输入统一社会信用代码"></el-input>
                </el-form-item>
                <!-- <el-form-item v-if="rowData.invoiceStatus == 5">
                    <el-button @click="handleApplyInvoice" type="primary" style="margin-top: 40px;text-align: right;">提交</el-button>
                </el-form-item> -->
                <el-row justify="center" align="middle">
                    <el-button @click="applyInvoice" type="primary" >提交</el-button>
                </el-row>
            </el-form>
            <!-- <iframe v-if="rowData.invoiceStatus == 15 && param.invoiceUrl && param.invoiceUrl.length > 0 && param.invoiceUrl[0].url"
                style="width:100%;height: auto;min-height: 400px;" :src="param.invoiceUrl[0].url + '#toolbar=0'">
            </iframe> -->
        </el-dialog>
        <!-- 查看提箱单 -->
        <!-- 查看提箱单列表 -->
        <el-dialog v-model="packingListDialog" title="提箱单列表">
            <el-table :data="packingListInfo" header-align="center" >
                <el-table-column property="packingNo" label="提箱单号" align="center">
                <template #default="scope">
                    <el-button link type="primary" size="default" @click.prevent="showPacking(scope.row)" >{{scope.row.packingNo}}</el-button>
                </template>
                </el-table-column>
                <el-table-column property="yardName" label="堆场名称" width="120" align="center"/>
                <el-table-column property="boxCondition" label="箱况" width="60" align="center"><!--箱况:boxCondition 5-全新   10-次新  15-适货 20-混提-->
                <template #default="scope">
                    <template v-if="scope.row.boxCondition == 5">全新</template>
                    <template v-if="scope.row.boxCondition == 10">次新</template>
                    <template v-if="scope.row.boxCondition == 15">适货</template>
                    <template v-if="scope.row.boxCondition == 20">混提</template>
                    <template v-else>--</template>
                </template>
                </el-table-column>
                <el-table-column property="residuePackingDays" label="剩余提箱天数" width="110" align="center">
                <template #default="scope">
                    {{scope.row.residuePackingDays}}天
                </template>
                </el-table-column>
                <el-table-column property="packingValidityPeriodStart" label="提箱单有效期范围" align="center">
                <template #default="scope">
                    {{ scope.row.packingValidityPeriodStart?.substring(0,10) }}~{{scope.row.packingValidityPeriodEnd?.substring(0,10)}}
                </template>
                </el-table-column>
                <el-table-column property="agentName" label="客户" show-overflow-tooltip align="center"/>
                <el-table-column property="packingStatus" label="状态" width="80" align="center">  <!--提箱单状态:  5-已发放 10-已下载 15-提箱中 20-已完成 25-作废 30-已过期-->
                <template #default="scope">
                    <template v-if="scope.row.packingStatus == 5">已发放</template>
                    <template v-if="scope.row.packingStatus == 10">已下载</template>
                    <template v-if="scope.row.packingStatus == 15">提箱中</template>
                    <template v-if="scope.row.packingStatus == 20">已完成</template>
                    <template v-if="scope.row.packingStatus == 25">作废</template>
                    <template v-if="scope.row.packingStatus == 30">已过期</template>
                    <template>--</template>
                </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 提箱单信息 -->
        <!-- <tixiangdanInfo ref="tixiangdanInfoRef" @tixiangdanInfoClick="txClick"  @tixiangdanInfoListClick="txListClick"></tixiangdanInfo> -->
        <el-dialog v-model="addTableItemDialog" title="新增还箱城市">
            <el-table ref="myTable" :data="addTableInfo" style="width: 100%;"> 
                <el-table-column prop="unitPrice" label="单价" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.unitPrice" placeholder="请输入单价" :formatter="formatterNumber" :parser="formatterNumber" class="el-price" style="width: 100%;">
                            <template #prefix>
                                <el-select v-model="scope.row.currency" placeholder="Select" style="width: 60px" >
                                    <el-option label="＄" value="USD"></el-option>
                                    <el-option label="￥" value="CNY"></el-option>
                                </el-select>
                            </template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="boxQuantity" label="预还量" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.boxQuantity" placeholder="请输入箱量" disabled oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" class="input-width"/>
                    </template>
                </el-table-column>
                <el-table-column prop="returnCity" label="还箱城市" align="center">
                    <template #default="scope">
                        <el-select v-model="scope.row.returnCityId" placeholder="请选择城市" filterable @change="changeCity" style="width: 100%">
                            <el-option v-for="(item,index) in scope.row.returnCity" :key="index" :label="item.cityCName" :value="item.id" :disabled="item.disabled"></el-option>
                        </el-select>
                        <!-- <el-select v-model="scope.row.returnCityId" filterable placeholder="Select" style="width: 100%">
                            <el-option v-for="item in cityList" :key="item.id" :label="item.cityCName" :value="item.id"/>
                        </el-select> -->
                    </template>
                </el-table-column>
                <el-table-column prop="city" align="center" width="50">
                    <template  #default="scope"><el-icon size="20" class="cursor" @click="handleDelete2(scope.$index)"><Remove /></el-icon></template>
                </el-table-column>
            </el-table>
            <el-row align="middle" class="marginTop20">
                <el-col :span="8">
                    <el-icon :size="25" color="#2158F3" class="cursor"  @click="handleAdd2"><CirclePlus /></el-icon>
                </el-col>
                <el-col :span="8" class="text-center">
                    <span class="_asterisk">结算流向：</span>
                    <template v-if="direction == '-1'">应付</template>
                    <template v-else-if="direction == '1'">应收</template>
                </el-col>
                <el-col :span="8" class="text-right">
                    <el-button type="primary" @click="addReturnCity">确定</el-button>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref,reactive, onMounted,computed, getCurrentInstance } from 'vue'
import  Carousel from '@/components/carousel'
import invoiceTemplate from '@/views/components/invoiceTemplate.vue'
import Steps from "@/views/placingOrder/exportOrder/component/steps"
import StepsTool from "@/views/placingOrder/exportOrder/component/steps-tool"
import Signature from '@/views/placingOrder/exportOrder/component/signature'
import OwnBox from '@/views/placingOrder/exportOrder/component/ownBox.vue'
import ExternalBox from '@/views/placingOrder/exportOrder/component/externalBox.vue';
import { useRoute,useRouter } from 'vue-router'
import { getOrderInfo,updateOrderInfo,cancelOrder,updateCityPriceOrderInfo } from '@/api/orderManage/index'
import { processApproved, processRejected } from '@/api/orderCheck/index'
import { addRentRequestInvoice, rentUploadingInvoice } from '@/api/invoice'
import { getEqbContractOrderInfo } from '@/api/contract/eQianBao'
import { ElMessage, ElLoading,ElMessageBox } from 'element-plus'
import  basicConfig from '@/constant/containerInfo'
import { userSimpleList } from '@/api/user/index'
import { getPackingData,rentBoxList } from '@/api/orderManage/packing'
import tixiangdanInfo from '@/views/components/order/tixiangdanInfo';
import Cookies from 'js-cookie'
import { formatDate } from '@/utils'
const route = useRoute()
const router = useRouter()
const companyRole = localStorage.getItem('companyRole')
const sourceType = computed(()=>{
    return route.query.sourceType // view：查看页面 edit：编辑页面
}) 

const businessRoleEnum = computed(()=>{
    return route.query.businessRoleEnum //公司类型: 5-贷代公司 10-集装箱公司 15-集卡公司 20-堆场公司
}) 
// const processBusinessType = ref(8) // 订单审核流程 5-出口箱审核 8-出口箱非管理员审核 20-出口箱箱东取消订单 25-出口箱货代取消订单
// const currentNodeType = ref(5) // 订单节点 出口箱:5-货代操作员提交 10-箱东操作员确认 30-E签宝签章

const direction = ref("-1")// 结算流向 -1：支出， 1-收入
const tableInfo = ref([
    {currency:"USD",unitPrice:"0",boxQuantity:0,cargoName:"",returnCityId:0,actualBoxQuantity:0,returnCity:[]} //默认数据
]) 

const tableInfoLength1 = ref(-1)
const tableInfoLength2 = ref(-1)
const repeatedSubscripts = ref(0)
const myTable = ref()
//添加提箱城市
const handleAdd1 = async() =>{ 
    if(repeatedSubscripts.value) return ElMessage.warning("还箱城市不能重复")
    const lastObject = {...tableInfo.value[tableInfo.value.length - 1]}
    if(tableInfo.value.length > 1){
        const lastSecondObject =  tableInfo.value[tableInfo.value.length - 2]
        if(lastSecondObject.returnCityId == lastObject.returnCityId){
            tableInfoLength1.value = tableInfo.value.length - 1 
            return ElMessage.warning("还箱城市不能重复")
        }
    }
    if(tableInfo.value.length> 9) return ElMessage.warning('最多添加10个还箱城市')
    tableInfo.value.push(lastObject)
    // scrollToBottom()

}
const addTableItemDialog = ref(false)
const cityList = ref(JSON.parse(localStorage.getItem('cityList') || '[]')) // 所有城市列表
const cityListCopy = JSON.parse(JSON.stringify(cityList.value));
const addTableInfo = ref([{currency:"USD",unitPrice:"0",boxQuantity:0,cargoName:"",returnCityId:'',returnCity:[]}])
const showAddReturnCity = () =>{ 
    cityListCopy.forEach(item => {
        const isCitySelected = tableInfo.value.some(tableItem => 
            Number(tableItem.returnCityId) === Number(item.id)
        );
        item.disabled = isCitySelected;
    })
    let item = [{currency:"USD",unitPrice:"0",boxQuantity:0,cargoName:"",returnCityId:'',returnCity:cityListCopy}]
    addTableInfo.value = item
    // addTableInfo.value[0].returnCity = cityListCopy
    addTableItemDialog.value = true
}

const handleAdd2 = () =>{
    const lastObject = {...addTableInfo.value[addTableInfo.value.length - 1]}
    if(addTableInfo.value.length > 1){
        const lastSecondObject =  addTableInfo.value[addTableInfo.value.length - 2]
        if(lastSecondObject.returnCityId == lastObject.returnCityId){
            return ElMessage.warning("还箱城市不能重复")
        }
    }
    if(addTableInfo.value.length> 4) return ElMessage.warning('最多添加5个还箱城市')
    addTableInfo.value.push(lastObject)
}
// 删除提箱城市
const handleDelete1 = (index:number) =>{
    if(tableInfo.value.length < 2) return ElMessage.warning('最少需保留一个还箱城市')
    tableInfo.value.splice(index,1)
}
const handleDelete2 = (index:number) =>{
    if(addTableInfo.value.length < 2) return ElMessage.warning('最少需保留一个还箱城市')
    addTableInfo.value.splice(index,1)
}


const addReturnCity = async() => {
    const cityPriceList: Array<{
        returnCityId: number | string;
        unitPrice: string;
        currency: string;
        boxQuantity: number | string;
    }> = []
    if(addTableInfo.value){
        addTableInfo.value.forEach(item=>{ 
            const data = {
                returnCityId: item.returnCityId,
                unitPrice: item.unitPrice,
                currency: item.currency,
                boxQuantity: item.boxQuantity
            }

            cityPriceList.push(data)
        }) 
    }
   
    await updateCityPriceOrderInfo(rowData.value.id,{cityPriceList:cityPriceList}).then(res => {
        if(res.code == "00000"){
            ElMessage.success("添加成功！")
            orderInfo()
            addTableItemDialog.value = false
        }else{
            ElMessage.warning(res.msg) 
        }
    })
}

const changeCity = (cityId:number) => { 
    const duplicateInfo = findDuplicateIndexes(tableInfo.value, 'returnCityId') || [];
    if(Array.isArray(duplicateInfo) && duplicateInfo.length > 1){
        repeatedSubscripts.value = 1
        tableInfoLength1.value = duplicateInfo[0]
        tableInfoLength2.value = duplicateInfo[1]
    }else{
        repeatedSubscripts.value = 0
        tableInfoLength1.value = -1
        tableInfoLength2.value = -1
    }
}
const tableRowClassName = ({row,rowIndex}) => {
    if (rowIndex == tableInfoLength1.value || rowIndex == tableInfoLength2.value) {
        return 'warning-row'
    }
    return ''
}


const totalBoxNum = computed(() => {
    let total = 0
    tableInfo.value.forEach(item => {
        total = total + Number(item.boxQuantity)
    })
    return total
})
const nickName = computed(()=>{
  return JSON.parse(Cookies.get("User-Info"))?.nickname
})
const paymentMethod = ref("5")
const _stepStatus = ref(2) // 当前订单状态 
const _cancellationStatus = ref(0) // 取消订单时的订单状态 [只有_stepStatus == 35 时 此参数才有效]
const _frontNodeReviewStatus = ref(0) // 上一个节点审核结果 5-通过 10-驳回
const _currentNodeType =  ref(0) // 订单节点
const rowData = ref({ // 订单基本信息
    id:'',
    orderNo:'',
    companyName:'',
    carryCityName:'',
    returnCityName:'',
    carryCountryName:'',
    returnCountryName:'',
    boxUsagePeriod:'',
    areaCode:'86',
    publisherName:'',
    publisherTel:'',
    unitPrice:'',
    currency:'',
    boxType:'',
    boxCondition:'',
    amount:'',
    boxQuantity:'',
    contacts:'',
    tel:'',
    planPickupDate:'',
    period:'',
    leaveMsg:'',
    processId:'',
    boxEastOperatorUserName:'',
    companyId:'',
    remark:'',
    packingAllocationQuantity:'',
    invoiceStatus:'5',
    invoiceType: '5',
    canceledType:'' //取消类型(5-箱东取消 10-货代取消)		
}) 
const total  = computed(()=>{ 
    const quantity = Number(rowData.value.boxQuantity) || 0
    const price = Number(rowData.value.unitPrice) || 0
    return (quantity * price).toFixed(2) // 保留两位小数，根据业务需要可调整
})
const rules = { 
    invoiceType:[
        { required: true, message: '发票类型必选', trigger: 'blur' }
    ],
    invoiceTitle:[
        { required: true, message: '企业名称必填', trigger: 'blur' },
        { pattern:/^[a-zA-Z\u4e00-\u9fa5]*$/, message: "只能输入英文和汉字", trigger: "blur" },
    ],
    invoiceTaxNum:[
        { required: true, message: '统一社会信用代码必填', trigger: 'blur' },
        { pattern:/^[0-9a-zA-Z]*$/, message: "只能输入数字和英文", trigger: "blur" },
    ]
}
interface UserSimple {
  userId: string | number
  nickname: string
}
const param = reactive({ 
    boxEastOperatorUserId:'', //操作员ID
    userSimpleList:[] as UserSimple[],
    packingInfo:[{
        id:'',
        orderNo:'',
        planPickupDate:'',
        createTime:'',
        packingAllocationQuantity:'',
        boxQuantity:'',
        needPackingNum:''
    }]
})

const allocation = ref([
    {
        businessUserId: '',           // 业务员id
        businessUserName: "",  // 业务员名称
        operateUserId: '',            // 操作员id
        operateUserName: "",   // 操作员名称
        businessNo: ""   // 业务编号
    }
])
const orderInfo = async() =>{ // 获取订单详情 
    if(!route.query.orderId) return ElMessage.warning('参数错误,请返回上一级并刷新页面')
    await getOrderInfo(route.query.orderId).then((res:any)=>{ 
        if(res.code == '00000'){
            rowData.value = res.data
            _stepStatus.value = res.data.status
            _cancellationStatus.value = res.data?.cancellationStatus || 0
            _frontNodeReviewStatus.value = res.data?.frontNodeReviewStatus || 0
            _currentNodeType.value = res.data?.currentNodeType || 0
            paymentMethod.value = res.data.paymentMethod.toString()
            // _stepStatus.value = 10
            // tableInfo.value = res.data.cityPriceList
           
            if(businessRoleEnum.value == "5"){ // 货代
                direction.value = String(res.data.agentDirection)
            }else if(businessRoleEnum.value == "10"){ //箱东
                direction.value = String(res.data.boxEastDirection)
            }
            const data = {currency:"USD",unitPrice:"1",boxQuantity:0,cargoName:"哈哈哈",returnCityId:0,actualBoxQuantity:0,returnCity:[]}
            tableInfo.value.splice(0, tableInfo.value.length)
            res.data.cityPriceList.forEach(item =>{
                data.currency = item.currency
                data.unitPrice = item.unitPrice
                data.boxQuantity = item.boxQuantity
                data.returnCityId = Number(item.returnCityId)
                data.actualBoxQuantity = Number(item.actualBoxQuantity)
                // if(res.data.status < 3){
                    data.returnCity =   JSON.parse(res.data.returnCity)
                // }else{
                //     const cityListCopy1 = JSON.parse(JSON.stringify(cityList.value));
                //     data.returnCity = cityListCopy1
                // }
               
                tableInfo.value.push({...data})
            })
            
            swiperData.list = res.data.mainFileList? JSON.parse(res.data?.mainFileList) : []
            param.packingInfo.length = 0
            let packingItem = {
                id: res.data.id,
                orderNo: res.data.orderNo,
                planPickupDate:res.data.planPickupDate,
                createTime:res.data.createTime,
                packingAllocationQuantity: res.data.packingAllocationQuantity,
                boxQuantity: res.data.boxQuantity,
                needPackingNum: res.data.boxQuantity - res.data.packingAllocationQuantity,
                boxType:res.data.boxType,
                boxCondition:res.data.boxCondition,
                carryCityId:res.data.carryCityId,
                returnCityId:res.data.returnCityId
            }
            param.packingInfo.push(packingItem)
            try{ 
                allocation.value = JSON.parse(res.data.allocation) 
            }catch(e){

            }
        }
    })

}
const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
  }
})


onMounted(()=>{ 
    orderInfo()
    userSimpleList({}).then(res=>{ 
        if(res.code == '00000' && res.data.length > 0){
            param.userSimpleList = res.data
            localStorage.setItem('userSimpleList', JSON.stringify(res.data))

            let nickName = JSON.parse(Cookies.get("User-Info"))?.nickname;
            param.boxEastOperatorUserId = Number(getOperatorUserId(nickName))
        }
        
    })
  
})

const toCancelOrder = () =>{ //货代取消租箱订单
    ElMessageBox.prompt('请输入订单取消原因', '提示', {
        confirmButtonText: '确认取消',
        cancelButtonText: '暂不取消',
        inputType: 'textarea', // 使用多行文本输入
        inputPlaceholder: '请输入取消原因...',
        inputValidator: (value) => {
            // 验证逻辑
            if (!value || value.trim() === '') return '取消原因不能为空！'; // 必填校验
            if (value.length > 500) return '取消原因不能超过500字符！'; // 长度校验
            return true; // 验证通过
        },
        inputErrorMessage: '请输入有效的取消原因', // 通用错误提示
    }).then(async({ value }) => {
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        let reqInfo = {
            id: rowData.value.id,
            remark: value
        };

        try {
            const res: any = await cancelOrder(reqInfo);
            if (res.code == "00000") {
                ElMessage.warning("申请取消订单取消成功");
                let pathUrl = ''
                if(companyRole=='zx'){ //货代
                    pathUrl = '/orderManageHD/rentOrder'
                }else if(companyRole=='putBox'){
                    pathUrl = '/orderManage/rentOrder';
                }
                router.replace({ path: pathUrl })
            }
        } catch (error) {
            ElMessage.error("取消失败");
        } finally {
            loading.close();
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消操作',
        })
    })
}

const confirmOrder =  async()=>{ //箱东确认租箱订单
    const hasDuplicates = new Set(tableInfo.value.map(item => item.returnCityId)).size !== tableInfo.value.length;
    if(hasDuplicates) return ElMessage.warning("还箱城市存在重复，请检查添加数据")
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    
    const cityPriceList: Array<{
        returnCityId: number | string;
        unitPrice: string;
        currency: string;
        boxQuantity: number | string;
    }> = []
    if(tableInfo.value){
        tableInfo.value.forEach(item=>{ 
            const data = {
                returnCityId: item.returnCityId,
                unitPrice: item.unitPrice,
                currency: item.currency,
                boxQuantity: item.boxQuantity
            }

            cityPriceList.push(data)
        }) 
    }

    try { 
        let reqUpdate = {
            id: rowData.value.id,
            // currency: rowData.value.currency,
            // unitPrice: rowData.value.unitPrice,
            boxUsagePeriod: rowData.value.boxUsagePeriod,
            // boxQuantity:rowData.value.boxQuantity,
            paymentMethod:paymentMethod.value,
            period:rowData.value.period,
            boxEastOperatorUserId: param.boxEastOperatorUserId,
            boxEastOperatorUserName: getOperatorUserName(param.boxEastOperatorUserId),
            planPickupDate:rowData.value.planPickupDate,
            specialNote:rowData.value.specialNote || '',
            cityPriceList: cityPriceList,
            agentDirection: direction.value
        }
        await updateOrderInfo(reqUpdate).then((res:any) => { 
            loading.close()
            if(res.code === "00000"){
                ElMessage({ message: '订单确认成功', type: 'success' })
                router.push({
                    path:'/orderManage/rentOrder',
                    query:{
                        tag: new Date().getTime()
                    }
                })
            }
        })
        const data = { "processId": rowData.value.processId }
        await processApproved(data).then((res:any) => {
            loading.close()
        })
    } catch (error) {
        ElMessage.error('确认失败')
    }finally {
        loading.close(); // 无论如何都关闭 loading
    }
}

const eqbDialog = ref(false)
const eqbUrl = ref('')
const signContract = async()=>{ //签署  
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const reqeQianBao = {
       orderId: rowData.value.id,
    //    companyId: rowData.value.companyId,
       businessType: 5  // 5:出口（租箱） 10：进口（回调） 15：购箱

    }
    await getEqbContractOrderInfo(reqeQianBao).then((res: any) => { 
        if(res.code == '00000'){
            eqbUrl.value = res.data.longContractUrl
        }
        loading.close()
        eqbDialog.value = true
    })
}


const getOperatorUserName = (id: string): string => {
    const user = param.userSimpleList.find(item => item.userId == id)
    return user ? user.nickname : ''
}
const getOperatorUserId = (name: string): string => {
    const user = param.userSimpleList.find(item => item.nickname == name)
    return user ? String(user.userId) : ''
}

const closeEQianBao = () => { //关闭e签宝 后刷新页面
    if(companyRole=='zx'){
        router.push({ 
            path:'/orderManageHD/rentOrder',
            query:{
                tag: new Date().getTime()
            }
        });
    }else if(companyRole=='putBox'){
        router.push({ 
            path:'/orderManage/rentOrder',
            query:{
                tag: new Date().getTime()
            }
        });
    }  
}

const { proxy } = getCurrentInstance()
const completeSigning = (id:any) => {  //完成签署
  let reqParam = { // 5:租箱 10：回调（进口） 15：购箱 
    orderId:id,
    businessType:5
  }
  proxy.$common(reqParam).then((res:any) => { 
    if(res.code == "200"){
      ElMessage.success('操作成功')
    }else{
      ElMessage.warning(res.msg)
    }
  })
}

const dackingDialog = ref(false)
const packingType = ref('5') // 5:自由箱 15：外调箱
const handlePacking = () => { // 开提箱单
    orderInfo()
    if(param.packingInfo[0].needPackingNum){
        dackingDialog.value = true
    }else{
        ElMessage.warning("所有集装箱都已开完提箱单，请勿重复操作！")
    }
   
}

const closeDialog = () => {  // 关闭提箱单弹窗
    dackingDialog.value = false
}
const invoiceDialog = ref(false)
//申请发票
const invoiceRef = ref()
const applyInvoice = () => {
    invoiceRef.value.validate(valid =>{
        if (valid) { 
            const data = {
                "invoiceOrder": JSON.stringify([{ orderId: rowData.value.id, orderNo: rowData.value.orderNo }]),
                "invoiceTitle": rowData.value.invoiceTitle?.trim(),
                "invoiceType": rowData.value.invoiceType,
                "invoiceContent": "租箱明细",
                "creditCode": rowData.value.invoiceTaxNum?.trim(),
                "payCurrency":  rowData.value.currency
               
            }
            addRentRequestInvoice(data).then((res: any) => {
                if(res.code == '00000'){
                    ElMessage.success('申请开票成功，请等待对方开具发票')
                    invoiceDialog.value= false
                }
              })
        }else{
            return false;
        }
    })
 
}

// 解约拒绝 
const rejected = () =>{
    ElMessageBox.prompt('请输入拒绝取消原因', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '关闭',
        inputType: 'textarea', // 使用多行文本输入
        inputPlaceholder: '请输入拒绝原因...',
        inputValidator: (value) => {
            // 验证逻辑
            if (!value || value.trim() === '') return '取消原因不能为空！'; // 必填校验
            if (value.length > 500) return '取消原因不能超过500字符！'; // 长度校验
            return true; // 验证通过
        },
        inputErrorMessage: '请输入有效的取消原因', // 通用错误提示
    }).then(async({ value }) => {
        const data = { "processId": rowData.value.processId,reviewRemark:value }
        processRejected(data).then((res:any) => {
            let pathUrl = ''
             if(companyRole=='zx'){ //货代
                pathUrl = '/orderManageHD/rentOrder'
            }else if(companyRole=='putBox'){
                pathUrl = '/orderManage/rentOrder';
            }
            router.replace({ path: pathUrl })
        })

    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消操作',
        })
    })


}
// 解约确认 
const approved = (source:any) =>{
    const data = { "processId": rowData.value.processId }
    let message = '解约成功'
    if(source == 2){ // 2：拒绝解约时调用
        message = '订单未取消，重新检查该订单'      
    }
    processApproved(data).then((res:any) => {
        ElMessage({
            type: 'success',
            message: message,
        })
        let pathUrl = ''
         if(companyRole=='zx'){ //货代
            pathUrl = '/orderManageHD/rentOrder'
        }else if(companyRole=='putBox'){
            pathUrl = '/orderManage/rentOrder';
        }
        router.replace({ path: pathUrl })
    })
}



//查看提箱单
const packingListDialog = ref(false)
const packingListInfo = ref()
const showPackingList = ()=>{
    rentBoxList(rowData.value.id).then((res: any) => {
        packingListDialog.value = true
        packingListInfo.value = res.data

  }).catch((err: any) => {
    ElMessage.warning("提箱单列表查询失败，请稍后再试")
  })
}
//提箱单详情
const tixiangdanInfoRef = ref()
const showPacking = async (val:any) => {
packingListDialog.value = false
  if (!val.packingId) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  tixiangdanInfoRef.value.openBox(val.packingId)
}

const copyText = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success('复制成功');
  } catch (err) {
    // ElMessage.error('复制失败'); // 使用 Element Plus 的错误提示
    fallbackCopyText(text)
  }
};

// 传统的复制方法（降级方案）
function fallbackCopyText(text) {
  try {
    // 创建一个临时的textarea元素来保存文本
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed'; // 避免滚动到底部
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.width = '2em';
    textArea.style.height = '2em';
    textArea.style.padding = '0';
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';
    textArea.style.zIndex = '-999'; // 放在不可见区域

    document.body.appendChild(textArea);
    textArea.focus(); // 聚焦
    textArea.select(); // 选择文本

    const successful = document.execCommand('copy'); // 执行复制命令
    document.body.removeChild(textArea); // 移除临时元素

    if (successful) {
        ElMessage.success('复制成功');
    } else {
      ElMessage.warning('复制失败，请手动选择文本进行复制。');
    }
  } catch (err) {
    ElMessage.warning('复制失败，请手动选择文本进行复制。');
  }
}



// 功能函数 
// 
//  查找重复属性值及其对应的所有下标
//  @param array 目标数组
//  @param property 要检查的属性
//  @returns 包含重复值和对应下标的Map
//  */
function findDuplicateIndexes<T>(
  array: T[], 
  property: keyof T
): Map<any, number[]> {
  const valueToIndexes = new Map<any, number[]>();
  
  array.forEach((item, index) => {
    const value = item[property];
    
    if (!valueToIndexes.has(value)) {
      valueToIndexes.set(value, [index]);
    } else {
      valueToIndexes.get(value)!.push(index);
    }
  });
  
  // 过滤出有重复的值
  let repeatedSubscripts:any
  // 遍历Map中的每个键值对
    for (const [key, value] of valueToIndexes) {
        // 遍历数组值
        // value.forEach((item, index) => {
        //     console.log(`  - 数组索引 ${index}: ${item}`);
        // });
        if(value.length > 1){
            repeatedSubscripts = value
        }
    }
  
//   const duplicates = new Map<any, number[]>();
//   for (const [value, indexes] of valueToIndexes) {
//     if (indexes.length > 1) {
//       duplicates.set(value, indexes);
//     }
//   }
    
  
  return repeatedSubscripts || [];
}

// 限制输入数值格式
const formatterNumber = (value:any) =>{ 
  const val = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')
  if (val.indexOf('.') === -1) {
    return (val- 0)
  }else {
    const valArr = val.split('.')
    return (valArr[0] - 0).toString() + '.' + valArr[1]
  }
}

</script>
<style lang="scss" scoped>
.city-title{
    font-weight: 500;
    font-size: 18px;
}
.city-content{
    color: #999;
}
.input-with-select{
    color: #ff0000;
}
.total{
    color: #ff0000;
    font-size: 24px;
    font-weight: 600;
}
.signature-position{
    position: absolute;
    top: 0;
    right: 0;
}

.el-price {
    :deep(.el-select__wrapper) {
        box-shadow: none !important;
    }

}
.el-table :deep(tr.warning-row) > td:nth-last-child(2) {
    border: 1px solid red !important;
}
</style>